#!/usr/bin/env bash
# A very lightweight version of linux-runner that
# doesn't support system emulation. Just useful
# to allow native or qemu-user mode emulation.

set -e

# shellcheck disable=SC1091
. /base-runner.sh

if [ -n "${CROSS_DEBUG}" ]; then
    set -x
fi

# arch in the rust target
arch="${1}"
shift

if [[ -z "${CROSS_RUNNER}" ]]; then
    if is_native_binary "${arch}"; then
        CROSS_RUNNER=native
    else
        CROSS_RUNNER=qemu-user
    fi
fi

# Ensure that the correct prefix is set even if the user has cleared the env.
# `@DEFAULT_QEMU_LD_PREFIX@` is replaced during image build.
export QEMU_LD_PREFIX=${QEMU_LD_PREFIX:-@DEFAULT_QEMU_LD_PREFIX@}

qarch=$(qemu_arch "${arch}")
case "${CROSS_RUNNER}" in
    native)
        exec "${@}"
        ;;
    qemu-user)
        exec "qemu-${qarch}" "${@}"
        ;;
    *)
        echo "Invalid runner: \"${CROSS_RUNNER}\"";
        echo "Valid runners are: native and qemu-user"
        exit 1
        ;;
esac
